#!/usr/bin/env bash

set -euo pipefail

trap 'rm -rf "$TMPDIR"' EXIT
TMPDIR=$(mktemp -d) || exit 1

case $(uname -m) in
"x86_64" | "aarch64")
  arch=$(uname -m)
  ;;
"arm64")
  arch="aarch64"
  ;;
*)
  echo "Unsupported cpu arch: $(uname -m)"
  exit 2
  ;;
esac

case $(uname -s) in
"Linux")
  sys="unknown-linux-musl"
  ;;
"Darwin")
  sys="apple-darwin"
  ;;
*)
  echo "Unsupported system: $(uname -s)"
  exit 2
  ;;
esac

APP_VERSION="$(curl -sSL https://api.github.com/repos/zellij-org/zellij/releases/latest | grep -Po '"tag_name": "\K[^"]*')"
DOWNLOAD_LINK="https://github.com/zellij-org/zellij/releases/download/${APP_VERSION}/zellij-$arch-$sys.tar.gz"

if [[ "${1:-}" == "--proxy" ]]; then
  DOWNLOAD_LINK="https://ghproxy.net/$DOWNLOAD_LINK"
fi
curl --location "$DOWNLOAD_LINK" | tar -C "$TMPDIR" -xz

sudo install "$TMPDIR/zellij" /usr/local/bin

mkdir -p ~/.config/zellij/
cp ./config/zellij/config.kdl ~/.config/zellij/config.kdl
